<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <!-- 作者ID查询 -->
   <!--   <el-form-item label="作者ID" prop="userId">
        <el-input
          v-model="queryParams.userId"
          placeholder="请输入作者ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->

      <!-- 作者昵称查询 -->
      <el-form-item label="作者昵称" prop="nickname">
        <el-input
          v-model="queryParams['users.nickname']"
          placeholder="请输入作者昵称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <!-- 分类查询 -->
      <el-form-item label="分类" prop="categoryId">
        <el-select v-model="queryParams.categoryTopId" placeholder="请选择一级分类" clearable @change="getCategories">
          <el-option
            v-for="item in categoryTopList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
        <el-select v-model="queryParams.categoryId" placeholder="请选择二级分类" clearable style="margin-left: 10px">
          <el-option
            v-for="item in categoriesList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>

      <!-- 审核状态查询 -->
      <el-form-item label="审核状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择审核状态" clearable>
          <el-option
            v-for="dict in dict.type.audit_status"
            :key="dict.value"
            :label="dict.label"
            :value="parseInt(dict.value)"
          />
        </el-select>
      </el-form-item>

      <!-- 媒体类型查询 -->
      <el-form-item label="媒体类型" prop="mediaType">
        <el-select v-model="queryParams.mediaType" placeholder="请选择媒体类型" clearable>
          <el-option
            v-for="item in mediaTypeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['recipes:recipes:edit']"
        >审核</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['recipes:recipes:remove']"
        >下架</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['recipes:recipes:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="recipesList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="id" align="center" prop="id" />
      <el-table-column label="作者信息" align="center">
        <template slot-scope="scope">
          <div>ID: {{ scope.row.userId }}</div>
          <div>昵称: {{ scope.row.users.nickname || '未知' }}</div>
        </template>
      </el-table-column>
      <el-table-column label="菜谱标题" align="center" prop="title" />


    <el-table-column label="封面图片" align="center" width="100">
      <template slot-scope="scope">
        <!-- 图片菜谱：直接展示路径对应的图片 -->
        <div v-if="scope.row.mediaType === 1">
          <image-preview
            :src="scope.row.coverUrl"
            :width="50"
            :height="50"
          />
        </div>
        <!-- 视频菜谱：展示视频封面（注意这里用了videoDescription字段） -->
        <div v-else-if="scope.row.mediaType === 2" >
          <image-preview
            :src="scope.row.videoDescription"
            :width="50"
            :height="50"
          />
        </div>
        <!-- 加载中提示（其他情况或加载状态） -->
        <el-loading v-else
          :text="'加载封面中'"
          :spinner="null"
          :background="null"
          style="width:50px;height:50px;"
        ></el-loading>
      </template>
    </el-table-column>







      <el-table-column label="菜谱简介" align="center" prop="introduction">
        <template slot-scope="scope">
          <div class="line-clamp">{{ scope.row.introduction }}</div>
        </template>
      </el-table-column>
 <!--     <el-table-column label="视频封面图" align="center" prop="videoDescription" /> -->
      <el-table-column label="时长(s)" align="center" prop="videoDuration" />
      <el-table-column label="浏览量" align="center" prop="viewCount" />
      <el-table-column label="耗时" align="center" prop="cookTimeOptions.name" />
      <el-table-column label="难度" align="center" prop="difficultyOptions.name" />
      <el-table-column label="分类" align="center">
        <template slot-scope="scope">
          {{ `${scope.row.categoryTop.name || '未知'}-${scope.row.categories.name || '未知'}` }}
        </template>
      </el-table-column>
      <el-table-column label="发布时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="审核状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.audit_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="收藏数" align="center" prop="collectCount" />
      <el-table-column label="媒体类型" align="center" prop="mediaType">
        <template slot-scope="scope">
          {{ scope.row.mediaType === 1 ? '图片' : '视频' }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['recipes:recipes:edit']"
          >审核</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['recipes:recipes:remove']"
          >下架</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 审核对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">

        <el-form-item label="菜谱标题" prop="title">
          <el-input v-model="form.title" disabled />
        </el-form-item>
        <el-form-item label="菜谱简介" prop="introduction">
          <el-input v-model="form.introduction" disabled />
        </el-form-item>


        <!-- 审核对话框中媒体内容区域修改 -->
        <el-form-item label="媒体内容" prop="coverUrl">
          <!-- 图片菜谱：展示路径对应的图片 -->
         <el-image
            v-if="form.mediaType === 1"

            :src="`http://localhost:8080${form.coverUrl}`"
            style="width: 300px; height: 200px; border: 1px solid #eee"
            fit="contain"
          />

          <!-- 视频菜谱：用路径播放视频（自动显示第一帧作为封面） -->
          <video
            v-if="form.mediaType === 2"
            :src="`http://localhost:8080${form.coverUrl}`"
            controls
            style="width: 300px; height: 200px; border: 1px solid #eee"
            preload="metadata">
            </video>
          <div v-if="form.mediaType === 2 && !form.coverUrl">暂无视频资源</div>
        </el-form-item>

        <el-form-item label="媒体类型" prop="mediaType">
          <el-input :value="form.mediaType === 1 ? '图片' : '视频'" disabled />
        </el-form-item>

        <el-form-item label="当前状态" prop="currentStatus">
          <el-input v-model="form.currentStatus" disabled />
        </el-form-item>
        <el-form-item label="审核结果" prop="status">
          <el-radio-group v-model="form.status">
           <el-radio
             v-for="item in dict.type.audit_status"
             :key="item.value"
             :label="parseInt(item.value)"
             :disabled="parseInt(item.value) === 0"
           >{{ item.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listRecipes, getRecipes, delRecipes, updateRecipes } from "@/api/recipes/recipes"
import { listCook_time_options } from "@/api/recipes/cook_time_options"
import { listOptions } from "@/api/recipes/options"
import { listCategories } from "@/api/recipes/categories"
import { listCategory_top } from "@/api/recipes/category_top"

export default {
  name: "Recipes",
  // 使用审核状态字典
  dicts: ['audit_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 菜谱主表表格数据
      recipesList: [],
      // 耗时选项列表
      cookTimeOptionsList: [],
      // 难度选项列表
      optionsList: [],

      // 媒体类型选项
      mediaTypeOptions: [
        { value: 1, label: '图片菜谱' },
        { value: 2, label: '视频菜谱' }
      ],

      // 二级分类列表
      categoriesList: [],
      // 一级分类列表
      categoryTopList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userId: null,
        'users.nickname': null, // 作者昵称查询参数（使用点号语法）
        title: null,
        mediaType: null,
        categoryId: null,
        status: null,
        categoryTopId: null // 一级分类ID
      },
      // 表单参数
      form: {
        id: null,
        status: 0,  // 审核结果
        currentStatus: "",// 当前状态文本
        coverUrl: "",
        introduction: "",
        title: "",
        mediaType: null,
        categoryTop: { id: null } // 直接设置categoryTop对象的id属性

      },
      // 表单校验
      rules: {
        status: [
          { required: true, message: "请选择审核结果", trigger: "change" }
        ]
      }
    }
  },
  computed: {
      filteredTwoCategories() {
        // 先判断 categoryTop 是否存在，不存在则返回空数组
        if (!this.form.categoryTop) return [];
        return this.categoriesList.filter(
          item => item.parentId === this.form.categoryTop.id
        );
      }
  },
  created() {
    this.getList()
    this.initFormRelatedData()
  },
  methods: {
    /** 查询菜谱主表列表 */
    getList() {
      // 使用点号语法传递嵌套属性
      const params = {
        ...this.queryParams,
        'categoryTop.id': this.queryParams.categoryTopId
      };

      // 删除多余的参数
      delete params.categoryTop;
      delete params.categoryTopId;

      this.loading = true;
      listRecipes(params).then(response => {
        this.recipesList = response.rows || []
        this.total = response.total || 0
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },



    /** 获取二级分类 */
    getCategories() {
      if (this.queryParams.categoryTopId) {
        listCategories({ parentId: this.queryParams.categoryTopId }).then(response => {
          this.categoriesList = response.rows || [];
          this.getList(); // 一级分类选择后查询菜谱
        });
      } else {
        this.categoriesList = [];
        this.getList(); // 一级分类清空后查询菜谱
      }
    },

    /** 初始化表单需要的关联数据 */
    initFormRelatedData() {
      // 加载耗时选项
      listCook_time_options().then(response => {
        this.cookTimeOptionsList = response.rows || []
      })

      // 加载难度选项
      listOptions().then(response => {
        this.optionsList = response.rows || []
      })

      // 加载一级分类
      listCategory_top().then(response => {
        this.categoryTopList = response.rows || []
      })
    },

    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },

    // 表单重置
    reset() {
      this.form = {
        id: null,
        status: 0,
        currentStatus: "",
        coverUrl: "",
        introduction: "",
        title: "",
        mediaType: null,
        categoryTop: { id: null }
      }

      this.resetForm("form")
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        userId: null,
        'users.nickname': null,
        title: null,
        mediaType: null,
        categoryId: null,
        status: null,
        categoryTopId: null
      }
      this.categoriesList = []
      this.handleQuery()
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },

    /** 审核按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids[0]
     getRecipes(id).then(response => {
       // 获取当前状态文本
       const statusText = this.dict.type.audit_status.find(
         item => parseInt(item.value) === response.data.status
       )?.label || "未知状态"

       this.form = {
         id: response.data.id,
         status: response.data.status,  // 默认显示当前状态
         currentStatus: statusText,
         coverUrl: response.data.coverUrl,
         introduction: response.data.introduction,
         title: response.data.title,
         mediaType: response.data.mediaType,
         categoryTop: response.data.categoryTop ? { id: response.data.categoryTop.id } : { id: null }
       }
      console.log("form.coverUrl:", this.form.coverUrl); // 打印图片路径
       this.open = true
       this.title = "审核菜谱"
     })
    },

    /** 提交审核结果 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 使用点号语法传递嵌套属性
          const submitData = {
            id: this.form.id,
            status: this.form.status,
            mediaType:this.form.mediaType,
          categoryTop: {
             id: this.form.categoryTop.id
           }
          }

          updateRecipes(submitData).then(response => {
            this.$modal.msgSuccess("审核操作成功")
            this.open = false
            this.getList()
          })
        }
      })
    },

    /** 下架按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认下架菜谱编号为"' + ids + '"的数据项？').then(() => {
        return delRecipes(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("下架成功")
      }).catch(() => {})
    },

    /** 导出按钮操作 */
    handleExport() {
      const params = {
        ...this.queryParams,
        'categoryTop.id': this.queryParams.categoryTopId
      };
      delete params.categoryTop;
      delete params.categoryTopId;

      this.download('recipes/recipes/export', params, `recipes_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>

<style scoped>
  .line-clamp {
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 3; /* 限制展示 3 行，可根据需要调整 */
    overflow: hidden;
  }
</style>
